const { Server } = require("socket.io");
const { onConnection } = require("./registeScoket.js");
const { isUnauthorized } = require("./util.js")
const { ServerFindUserAccount, ServerSetUserSockId, ServerGetUserSockIdByID, ServerUpdataUserSockId, ServerGetUserSockIdBySocketID, ServerDestroySocket, ServerFinduserGroup } = require("../../server/user/index.js")
class Socket {
    io
    initSocket(httpServer) {
        this.io = new Server(httpServer, {
            cors: {
                origin: "*",
                allowedHeaders: ["token"],
            },
            transports: ['websocket', 'polling'],
            connectionStateRecovery: {
                // 会话和报文的备份时间
                maxDisconnectionDuration: 2 * 60 * 1000,
                // 恢复成功后是否跳过中间件
                skipMiddlewares: false,
            }
        });
        this.io.use(async (socket, next) => {
            const token = socket.handshake.auth.token;
            const fleg = await isUnauthorized(token);
            if (fleg) {
                const userAccount = fleg.userAccount
                const findUserAccountRes = await ServerFindUserAccount(userAccount)
                try {
                    if (findUserAccountRes.isok) {
                        const GetUserSockIdres = await ServerGetUserSockIdByID(Number(findUserAccountRes.data.userId));
                        if (GetUserSockIdres.isok) {
                            if (true) {
                                const UpdataUserSockIdRes = await ServerUpdataUserSockId(findUserAccountRes.data.userId, socket.id)
                                if (UpdataUserSockIdRes.isok) {
                                    ServerFinduserGroup(findUserAccountRes.data.userId).then((userGroupres) => {
                                        if (userGroupres.isok) {
                                            userGroupres.data.map(socketRoom => {
                                                socket.join(socketRoom); // 将指定的 socket 加入到房间
                                            })
                                        }
                                    })
                                    next()
                                } else {
                                    const err = new Error("");
                                    err.data = { content: "更新sockid失败" };
                                    next(err);
                                }
                            } else {
                                next()
                                console.log("该账号有socket链接");
                            }
                        } else {
                            const UserSockIdres = await ServerSetUserSockId(findUserAccountRes.data.userId, socket.id);
                            if (UserSockIdres.isok) {
                                next()
                            } else {
                                const err = new Error("");
                                err.data = { content: "token错误" };
                                next(err);
                            }
                        }
                    } else {
                        const err = new Error("not user");
                        err.data = { content: "没有用户信息" };
                        next(err);
                    }
                } catch (error) {
                    console.log(error);
                }
            } else {
                const err = new Error("not authorized");
                err.data = { content: "token错误" };
                next(err);
            }
        });
        this.io.on("connection", (socket) => {
            console.log("有服务链接", socket.id);
            onConnection(this.io, socket)
            socket.on("disconnect", async (reason) => {
                console.log("断开链接", socket.id);
                const GetUserSockIdBySocketIDRes = await ServerGetUserSockIdBySocketID(socket.id);
                if (GetUserSockIdBySocketIDRes.isok) {
                    const UpdataUserSockIdRes = await ServerUpdataUserSockId(GetUserSockIdBySocketIDRes.data.userId, null)
                    if (UpdataUserSockIdRes.isok) {
                        console.log("删除socketid成功");
                    } else {
                        console.log("删除socketid失败");
                        const DestroySocketRes = await ServerDestroySocket(GetUserSockIdBySocketIDRes.data.id)
                        if (DestroySocketRes.isok) {
                            console.log("账号记录已删除");
                        }
                    }
                }
            });
        });
    }
}

module.exports = new Socket()